package home.game.management;

import home.game.entity.User;

import javax.persistence.EntityManager;
import javax.persistence.Persistence;
import javax.persistence.Query;
import java.util.Date;
import java.util.List;

/**
 */
public class UserManager {
    private static final String UNIT_USER = "UserManager";
    private static final int MAX_TOP_SCORES = 10;
    private EntityManager em;

    public void initTransaction() {
        em = Persistence.createEntityManagerFactory(UNIT_USER).createEntityManager();
    }

    public User findUser(String userName) {
        User result;
        try {
            Query q = em.createNamedQuery(User.FIND_BY_NAME);
            q.setParameter("name", userName);
            result = (User) q.getSingleResult();
            return (User) result.clone();
        } catch (Exception e) {
            return createNewUser(userName);
        }

    }

    public User createNewUser(String userName) {
        em.getTransaction().begin();
        User newUser = new User();
        newUser.setPlayerName(userName);
        newUser.setLastPlayed(new Date());
        em.persist(newUser);
        em.getTransaction().commit();
        return newUser;
    }

    public void updateUserScore(User user) {
        em.getTransaction().begin();
        User updateUser;
        if (user.getId() != 0) {
            updateUser = em.find(User.class, user.getId());
            updateUser.setScore(user.getScore());
            updateUser.setLastPlayed(new Date());

        } else {
            updateUser = user;
            updateUser.setLastPlayed(new Date());
        }

        em.persist(updateUser);
        em.getTransaction().commit();

    }


    public List<User> getTopScores() {
        Query q = em.createNamedQuery(User.FIND_TOP_SCORES);
        q.setMaxResults(MAX_TOP_SCORES);
        return q.getResultList();
    }

}
